import React, { useState, useEffect, useCallback } from 'react';
import {
  Card,
  Timeline,
  Button,
  Space,
  Tag,
  Tooltip,
  Modal,
  Input,
  message,
  Empty,
  Drawer,
  Row,
  Col,
  Badge,
  Popconfirm,
  Alert
} from 'antd';
import {
  ClockCircleOutlined,
  SaveOutlined,
  RollbackOutlined,
  DiffOutlined,
  StarOutlined,
  StarFilled,
  DeleteOutlined,
  EditOutlined,
  CopyOutlined,
  CheckCircleOutlined,
  ExclamationCircleOutlined,
  TagOutlined,
  BranchesOutlined
} from '@ant-design/icons';
import { PromptVersion, PromptTemplate } from '@/types/prompt';
// TODO: 需要安装 react-diff-viewer-continued 包
// import DiffViewer from 'react-diff-viewer-continued';
import './style.css';

const { TextArea } = Input;

interface PromptVersionHistoryProps {
  promptId: string;
  currentVersion?: number;
  versions?: PromptVersion[];
  onSaveVersion?: (content: string, changelog?: string) => Promise<void>;
  onLoadVersion?: (version: PromptVersion) => void;
  onCompareVersions?: (v1: PromptVersion, v2: PromptVersion) => void;
  onDeleteVersion?: (versionId: string) => Promise<void>;
  maxVersions?: number;
  className?: string;
}

const PromptVersionHistory: React.FC<PromptVersionHistoryProps> = ({
  promptId,
  currentVersion = 1,
  versions: propVersions = [],
  onSaveVersion,
  onLoadVersion,
  onCompareVersions,
  onDeleteVersion,
  maxVersions = 30,
  className = ''
}) => {
  const [versions, setVersions] = useState<PromptVersion[]>(propVersions);
  const [selectedVersion, setSelectedVersion] = useState<PromptVersion | null>(null);
  const [compareMode, setCompareMode] = useState(false);
  const [compareVersions, setCompareVersions] = useState<[PromptVersion | null, PromptVersion | null]>([null, null]);
  const [showSaveModal, setShowSaveModal] = useState(false);
  const [changelog, setChangelog] = useState('');
  const [versionTag, setVersionTag] = useState('');
  const [starredVersions, setStarredVersions] = useState<string[]>([]);
  const [showDiffDrawer, setShowDiffDrawer] = useState(false);
  const [searchQuery, setSearchQuery] = useState('');

  // 初始化版本列表
  useEffect(() => {
    setVersions(propVersions);
  }, [propVersions]);

  // 过滤版本
  const filteredVersions = versions.filter(v => {
    if (!searchQuery) return true;
    const query = searchQuery.toLowerCase();
    return (
      v.changelog?.toLowerCase().includes(query) ||
      v.tag?.toLowerCase().includes(query) ||
      v.content.toLowerCase().includes(query) ||
      `v${v.version}`.includes(query)
    );
  });

  // 保存新版本
  const handleSaveVersion = useCallback(async () => {
    if (!onSaveVersion) {
      message.error('保存功能未配置');
      return;
    }

    if (versions.length >= maxVersions) {
      Modal.confirm({
        title: '版本数量已达上限',
        content: `当前已有 ${versions.length} 个版本，最多保留 ${maxVersions} 个版本。保存新版本将删除最旧的非星标版本。是否继续？`,
        onOk: async () => {
          // 找到最旧的非星标版本
          const oldestNonStarred = versions.find(v => !starredVersions.includes(v.id));
          if (oldestNonStarred && onDeleteVersion) {
            await onDeleteVersion(oldestNonStarred.id);
          }
          // 保存新版本
          await onSaveVersion('', changelog);
          setShowSaveModal(false);
          setChangelog('');
          message.success('版本已保存');
        }
      });
    } else {
      await onSaveVersion('', changelog);
      setShowSaveModal(false);
      setChangelog('');
      message.success('版本已保存');
    }
  }, [onSaveVersion, changelog, versions, maxVersions, starredVersions, onDeleteVersion]);

  // 切换版本
  const handleLoadVersion = useCallback((version: PromptVersion) => {
    Modal.confirm({
      title: '切换版本',
      content: `确定要切换到版本 v${version.version} 吗？当前的修改将会丢失。`,
      onOk: () => {
        if (onLoadVersion) {
          onLoadVersion(version);
          setSelectedVersion(version);
          message.success(`已切换到版本 v${version.version}`);
        }
      }
    });
  }, [onLoadVersion]);

  // 版本对比
  const handleCompare = useCallback(() => {
    if (compareVersions[0] && compareVersions[1]) {
      setShowDiffDrawer(true);
      if (onCompareVersions) {
        onCompareVersions(compareVersions[0], compareVersions[1]);
      }
    } else {
      message.warning('请选择两个版本进行对比');
    }
  }, [compareVersions, onCompareVersions]);

  // 选择对比版本
  const handleSelectCompareVersion = useCallback((version: PromptVersion) => {
    if (compareMode) {
      const [v1, v2] = compareVersions;
      if (!v1) {
        setCompareVersions([version, v2]);
      } else if (!v2 && v1.id !== version.id) {
        setCompareVersions([v1, version]);
      } else {
        setCompareVersions([version, null]);
      }
    }
  }, [compareMode, compareVersions]);

  // 切换星标
  const toggleStar = useCallback((versionId: string) => {
    if (starredVersions.includes(versionId)) {
      setStarredVersions(starredVersions.filter(id => id !== versionId));
      message.info('已取消星标');
    } else {
      setStarredVersions([...starredVersions, versionId]);
      message.success('已添加星标');
    }
  }, [starredVersions]);

  // 删除版本
  const handleDeleteVersion = useCallback(async (version: PromptVersion) => {
    if (version.version === currentVersion) {
      message.error('不能删除当前版本');
      return;
    }

    if (onDeleteVersion) {
      await onDeleteVersion(version.id);
      setVersions(versions.filter(v => v.id !== version.id));
      message.success('版本已删除');
    }
  }, [currentVersion, onDeleteVersion, versions]);

  // 复制版本内容
  const handleCopyContent = useCallback((content: string) => {
    navigator.clipboard.writeText(content).then(() => {
      message.success('已复制到剪贴板');
    });
  }, []);

  // 格式化时间
  const formatTime = (date: Date) => {
    const d = new Date(date);
    const now = new Date();
    const diffMs = now.getTime() - d.getTime();
    const diffMins = Math.floor(diffMs / 60000);
    
    if (diffMins < 1) return '刚刚';
    if (diffMins < 60) return `${diffMins}分钟前`;
    if (diffMins < 1440) return `${Math.floor(diffMins / 60)}小时前`;
    if (diffMins < 10080) return `${Math.floor(diffMins / 1440)}天前`;
    
    return d.toLocaleDateString('zh-CN');
  };

  // 渲染版本项
  const renderVersionItem = (version: PromptVersion) => {
    const isCurrent = version.version === currentVersion;
    const isStarred = starredVersions.includes(version.id);
    const isSelected = selectedVersion?.id === version.id;
    const isCompareSelected = compareVersions.some(v => v?.id === version.id);

    return (
      <Timeline.Item
        key={version.id}
        color={isCurrent ? 'green' : isStarred ? 'gold' : 'gray'}
        dot={
          <div className="version-dot">
            {isCurrent ? (
              <CheckCircleOutlined />
            ) : isStarred ? (
              <StarFilled />
            ) : (
              <ClockCircleOutlined />
            )}
          </div>
        }
      >
        <Card
          className={`version-card ${isCurrent ? 'current' : ''} ${isSelected ? 'selected' : ''} ${isCompareSelected ? 'compare-selected' : ''}`}
          hoverable
          onClick={() => compareMode ? handleSelectCompareVersion(version) : setSelectedVersion(version)}
        >
          <Row align="middle">
            <Col flex="auto">
              <Space direction="vertical" size={4}>
                <Space>
                  <span className="version-number">v{version.version}</span>
                  {isCurrent && <Tag color="green">当前版本</Tag>}
                  {version.tag && <Tag color="blue">{version.tag}</Tag>}
                  {version.draft && <Tag color="orange">草稿</Tag>}
                </Space>
                {version.changelog && (
                  <div className="version-changelog">{version.changelog}</div>
                )}
                <Space className="version-meta">
                  <span>{formatTime(version.createdAt)}</span>
                  <span>由 {version.createdBy}</span>
                </Space>
              </Space>
            </Col>
            <Col>
              <Space>
                {compareMode ? (
                  <Badge
                    count={compareVersions[0]?.id === version.id ? 1 : compareVersions[1]?.id === version.id ? 2 : 0}
                    style={{ backgroundColor: '#1890ff' }}
                  />
                ) : (
                  <>
                    <Tooltip title={isStarred ? '取消星标' : '添加星标'}>
                      <Button
                        size="small"
                        type="text"
                        icon={isStarred ? <StarFilled style={{ color: '#faad14' }} /> : <StarOutlined />}
                        onClick={(e) => {
                          e.stopPropagation();
                          toggleStar(version.id);
                        }}
                      />
                    </Tooltip>
                    <Tooltip title="复制内容">
                      <Button
                        size="small"
                        type="text"
                        icon={<CopyOutlined />}
                        onClick={(e) => {
                          e.stopPropagation();
                          handleCopyContent(version.content);
                        }}
                      />
                    </Tooltip>
                    {!isCurrent && (
                      <>
                        <Tooltip title="切换到此版本">
                          <Button
                            size="small"
                            type="text"
                            icon={<RollbackOutlined />}
                            onClick={(e) => {
                              e.stopPropagation();
                              handleLoadVersion(version);
                            }}
                          />
                        </Tooltip>
                        {onDeleteVersion && (
                          <Popconfirm
                            title="确定要删除这个版本吗？"
                            onConfirm={(e) => {
                              e?.stopPropagation();
                              handleDeleteVersion(version);
                            }}
                            onCancel={(e) => e?.stopPropagation()}
                          >
                            <Tooltip title="删除版本">
                              <Button
                                size="small"
                                type="text"
                                danger
                                icon={<DeleteOutlined />}
                                onClick={(e) => e.stopPropagation()}
                              />
                            </Tooltip>
                          </Popconfirm>
                        )}
                      </>
                    )}
                  </>
                )}
              </Space>
            </Col>
          </Row>
        </Card>
      </Timeline.Item>
    );
  };

  return (
    <div className={`prompt-version-history ${className}`}>
      <Card
        title={
          <Space>
            <BranchesOutlined />
            <span>版本历史</span>
            <Badge count={versions.length} style={{ backgroundColor: '#52c41a' }} />
          </Space>
        }
        extra={
          <Space>
            <Input.Search
              placeholder="搜索版本"
              size="small"
              style={{ width: 150 }}
              value={searchQuery}
              onChange={e => setSearchQuery(e.target.value)}
              allowClear
            />
            <Button
              icon={<SaveOutlined />}
              onClick={() => setShowSaveModal(true)}
              disabled={!onSaveVersion}
            >
              保存版本
            </Button>
            <Button
              icon={<DiffOutlined />}
              type={compareMode ? 'primary' : 'default'}
              onClick={() => {
                setCompareMode(!compareMode);
                setCompareVersions([null, null]);
              }}
            >
              {compareMode ? '退出对比' : '版本对比'}
            </Button>
          </Space>
        }
      >
        {compareMode && (
          <Alert
            message="版本对比模式"
            description="请点击选择两个版本进行对比"
            type="info"
            showIcon
            closable
            onClose={() => setCompareMode(false)}
            action={
              <Button
                size="small"
                type="primary"
                onClick={handleCompare}
                disabled={!compareVersions[0] || !compareVersions[1]}
              >
                开始对比
              </Button>
            }
            style={{ marginBottom: 16 }}
          />
        )}

        {filteredVersions.length === 0 ? (
          <Empty
            description={searchQuery ? '没有找到匹配的版本' : '暂无版本历史'}
            image={Empty.PRESENTED_IMAGE_SIMPLE}
          />
        ) : (
          <Timeline mode="left">
            {filteredVersions.map(renderVersionItem)}
          </Timeline>
        )}

        {versions.length > 0 && (
          <div className="version-stats">
            <Space split={<span>•</span>}>
              <span>共 {versions.length} 个版本</span>
              <span>{starredVersions.length} 个星标版本</span>
              <span>最多保留 {maxVersions} 个版本</span>
            </Space>
          </div>
        )}
      </Card>

      {/* 保存版本Modal */}
      <Modal
        title="保存新版本"
        open={showSaveModal}
        onOk={handleSaveVersion}
        onCancel={() => {
          setShowSaveModal(false);
          setChangelog('');
          setVersionTag('');
        }}
        okText="保存"
        cancelText="取消"
      >
        <Space direction="vertical" style={{ width: '100%' }} size={16}>
          <div>
            <div style={{ marginBottom: 8 }}>版本说明：</div>
            <TextArea
              value={changelog}
              onChange={e => setChangelog(e.target.value)}
              placeholder="请输入此版本的修改说明..."
              rows={4}
              showCount
              maxLength={200}
            />
          </div>
          <div>
            <div style={{ marginBottom: 8 }}>版本标签（可选）：</div>
            <Input
              value={versionTag}
              onChange={e => setVersionTag(e.target.value)}
              placeholder="例如：稳定版、测试版"
              prefix={<TagOutlined />}
              maxLength={20}
            />
          </div>
        </Space>
      </Modal>

      {/* 版本对比Drawer */}
      <Drawer
        title="版本对比"
        placement="right"
        width="80%"
        open={showDiffDrawer}
        onClose={() => setShowDiffDrawer(false)}
        extra={
          <Space>
            <Tag color="red">v{compareVersions[0]?.version}</Tag>
            <span>VS</span>
            <Tag color="green">v{compareVersions[1]?.version}</Tag>
          </Space>
        }
      >
        {compareVersions[0] && compareVersions[1] && (
          <div className="diff-viewer-container">
            {/* TODO: 需要安装 react-diff-viewer-continued 包来显示差异对比 */}
            <div style={{ display: 'flex', gap: '16px' }}>
              <div style={{ flex: 1 }}>
                <h4>版本 {compareVersions[0].version}</h4>
                <pre style={{ background: '#f5f5f5', padding: '12px', borderRadius: '4px', whiteSpace: 'pre-wrap' }}>
                  {compareVersions[0].content}
                </pre>
              </div>
              <div style={{ flex: 1 }}>
                <h4>版本 {compareVersions[1].version}</h4>
                <pre style={{ background: '#f5f5f5', padding: '12px', borderRadius: '4px', whiteSpace: 'pre-wrap' }}>
                  {compareVersions[1].content}
                </pre>
              </div>
            </div>
          </div>
        )}
      </Drawer>

      {/* 版本详情Modal */}
      {selectedVersion && !compareMode && (
        <Modal
          title={`版本详情 - v${selectedVersion.version}`}
          open={!!selectedVersion}
          onCancel={() => setSelectedVersion(null)}
          footer={[
            <Button key="copy" icon={<CopyOutlined />} onClick={() => handleCopyContent(selectedVersion.content)}>
              复制内容
            </Button>,
            <Button
              key="load"
              type="primary"
              icon={<RollbackOutlined />}
              onClick={() => handleLoadVersion(selectedVersion)}
              disabled={selectedVersion.version === currentVersion}
            >
              切换到此版本
            </Button>
          ]}
          width={800}
        >
          <Space direction="vertical" style={{ width: '100%' }} size={16}>
            <Card size="small">
              <Row gutter={16}>
                <Col span={12}>
                  <div className="detail-item">
                    <span className="detail-label">版本号：</span>
                    <span>v{selectedVersion.version}</span>
                  </div>
                </Col>
                <Col span={12}>
                  <div className="detail-item">
                    <span className="detail-label">创建时间：</span>
                    <span>{new Date(selectedVersion.createdAt).toLocaleString('zh-CN')}</span>
                  </div>
                </Col>
                <Col span={12}>
                  <div className="detail-item">
                    <span className="detail-label">创建者：</span>
                    <span>{selectedVersion.createdBy}</span>
                  </div>
                </Col>
                <Col span={12}>
                  <div className="detail-item">
                    <span className="detail-label">标签：</span>
                    {selectedVersion.tag ? <Tag color="blue">{selectedVersion.tag}</Tag> : <span>无</span>}
                  </div>
                </Col>
              </Row>
              {selectedVersion.changelog && (
                <div className="detail-item" style={{ marginTop: 12 }}>
                  <span className="detail-label">版本说明：</span>
                  <div style={{ marginTop: 8 }}>{selectedVersion.changelog}</div>
                </div>
              )}
            </Card>
            <Card size="small" title="提示词内容">
              <pre className="version-content-preview">{selectedVersion.content}</pre>
            </Card>
          </Space>
        </Modal>
      )}
    </div>
  );
};

export default PromptVersionHistory;